//  基于wxpage.js 优化其$redirect $route等route跳转函数 适应项目目录

const WXPage = require('../../static/wxpage')

const ROUTE_CACHE_KEY = 'a-route-page-from'

let cacheTime = 1000 * 60 * 60 * 3

function handlePageArgs(name, query) {
  let s
  if (name.indexOf('?') > -1) {
    let urlArr = name.split('?')
    s = '/pages/' + urlArr[0] + '/index?' + urlArr[1]
  } else {
    s = '/pages/' + name + '/index'
    if (query) {
      s += '?' + query
    }
  }
  return s
}

function setRouteCache(context) {
  WXPage.cache.set(ROUTE_CACHE_KEY, context.$curPage().$pageName, cacheTime);
}

function getRouteCache(context) {
  return WXPage.cache.get(ROUTE_CACHE_KEY);
}

function routeTo(method, pageName, query, options = {}) {
  WXPage.cache.set(ROUTE_CACHE_KEY, pageName, cacheTime);

  wx[method]({
    url: `/pages/${pageName}/index` + (query ? `?${query}` : ''),
    ...options
  })
}

function navigateTo(pageName, query, options) {
  routeTo('navigateTo', pageName, query, options)
}

function redirectTo(pageName, query, options) {
  routeTo('redirectTo', pageName, query, options)
}

function switchTab(pageName, query, options) {
  routeTo('switchTab', pageName, query, options)
}


module.exports = {
  handlePageArgs,
  setRouteCache,
  getRouteCache,
  navigateTo,
  redirectTo,
  switchTab,
}
